﻿using System;
using System.Windows;
using System.Windows.Media.Animation;
using Hardcodet.Wpf.TaskbarNotification.Interop;

namespace CustomerAssistant
{
    public static class TrayNotifyUtil
    {
        public static readonly object SyncRoot = new object();
        static Window TrayMenuWnd = null;
        static bool TrayMenuIsOpen = false;
        static NotifyIconData IconData;
        static IconDataMembers TrayIconFlag;
        static System.Timers.Timer FlashTimer = null;

        /// <summary>
        /// Updates the taskbar icons with data provided by a given
        /// <see cref="NotifyIconData"/> instance.
        /// </summary>
        /// <param name="data">Configuration settings for the NotifyIcon.</param>
        /// <param name="command">Operation on the icon (e.g. delete the icon).</param>
        /// <param name="flags">Defines which members of the <paramref name="data"/>
        /// structure are set.</param>
        /// <returns>True if the data was successfully written.</returns>
        /// <remarks>See Shell_NotifyIcon documentation on MSDN for details.</remarks>
        public static bool WriteIconData(ref NotifyIconData data, NotifyCommand command, IconDataMembers flags)
        {
            IconData = data;
            TrayIconFlag = flags;
            data.ValidMembers = flags;
            lock (SyncRoot)
            {
                return WinApi.Shell_NotifyIcon(command, ref data);
            }
        }

        public static void FlashTrayIcon()
        {
            if (FlashTimer == null)
            {
                FlashTimer = new System.Timers.Timer();
                FlashTimer.Elapsed += new System.Timers.ElapsedEventHandler((a, b) =>
                {
                    IconData.IconHandle = (IconData.IconHandle == IntPtr.Zero ? CustomerAssistant.Properties.Resource.status_icon.Handle : IntPtr.Zero);
                    WriteIconData(ref IconData, NotifyCommand.Modify, TrayIconFlag);
                });
                FlashTimer.Interval = 500;
            }
            FlashTimer.Start();
        }

        public static void StopFlashTrayIcon()
        {
            if (FlashTimer != null)
            {
                FlashTimer.Stop();
                IconData.IconHandle = CustomerAssistant.Properties.Resource.status_icon.Handle;
                WriteIconData(ref IconData, NotifyCommand.Modify, TrayIconFlag);
            }
        }

        public static void PopupTrayMenu(WindowMessageSink messageSink)
        {
            if (TrayMenuIsOpen) return;
            Hardcodet.Wpf.TaskbarNotification.Interop.Point cursorPosition = new Hardcodet.Wpf.TaskbarNotification.Interop.Point();
            WinApi.GetCursorPos(ref cursorPosition);
            TrayMenuWnd = new Window();
            var menu = new TrayMenu();
            TrayMenuWnd.AllowsTransparency = true;
            TrayMenuWnd.Content = menu;
            TrayMenuWnd.Topmost = true;
            TrayMenuWnd.ShowInTaskbar = false;
            TrayMenuWnd.ResizeMode = ResizeMode.NoResize;
            TrayMenuWnd.WindowStyle = WindowStyle.None;
            TrayMenuWnd.Width = menu.Width;
            TrayMenuWnd.Height = menu.Height;
            TrayMenuWnd.Left = cursorPosition.X - (double.IsNaN(TrayMenuWnd.Width) ? TrayMenuWnd.MinWidth : TrayMenuWnd.Width);
            TrayMenuWnd.Top = SystemParameters.WorkArea.Height - (double.IsNaN(TrayMenuWnd.Height) ? TrayMenuWnd.MinHeight : TrayMenuWnd.Height);
            TrayMenuWnd.ShowActivated = true;
            TrayMenuWnd.Show();
            TrayMenuIsOpen = true;
            TrayMenuWnd.Closed += new EventHandler((a, b) =>
            {
                TrayMenuIsOpen = false;
            });
            WinApi.SetForegroundWindow(messageSink.MessageWindowHandle);
        }

        public static void ShowInfoTip(Window wnd, InfoTip tip, string positionStr, bool isModal = true, bool fadeEffect = false)
        {
            wnd.Width = tip.Width;
            wnd.Height = tip.Height;
            wnd.AllowsTransparency = true;
            wnd.WindowStyle = WindowStyle.None;
            wnd.Content = tip;
            wnd.Topmost = true;
            tip.FadeEffect = fadeEffect;
            if (string.Compare(positionStr, "RB", true) == 0)
            {
                //右下角
                wnd.Left = SystemParameters.PrimaryScreenWidth - tip.Width;
                wnd.Top = SystemParameters.WorkArea.Height - tip.Height;
            }
            else if (string.Compare(positionStr, "SC", true) == 0)
            {
                //屏幕中间
                wnd.Left = (SystemParameters.PrimaryScreenWidth - tip.Width) / 2;
                wnd.Top = (SystemParameters.WorkArea.Height - tip.Height) / 2;
            }
            if (fadeEffect)
            {
                DoubleAnimation OpercityAnimation = new DoubleAnimation(0.01, 1.00, new Duration(TimeSpan.FromMilliseconds(200)));
                wnd.BeginAnimation(Window.OpacityProperty, OpercityAnimation);
            }
            if (isModal)
                wnd.ShowDialog();
            else
                wnd.Show();
        }

        public static void CloseTrayMenu()
        {
            if (TrayMenuWnd != null && TrayMenuIsOpen)
            {
                try
                {
                    TrayMenuWnd.Close();
                }
                catch { }
            }
        }
    }
}